require(['init'], function () {
    var $J_teacher_appoint = $('<div class="teacher-appoint" id="J_teacher_appoint" style="width:100%;">' +
        '<input type="hidden" id="oruid">' +
        '<input type="hidden" class="studentuid">' +
        '<input class="form-control " type="hidden" id="studentname">' +
        '<input class="form-control " type="hidden" id="coursename" >' +
        '<div class="line"></div>' +
        '<div class="TeachersQuery" style="width: 55%; float: left; border-bottom：none !important; height:100%; margin-top: 20px; border-radius: 5px">' +
        '<div class="topbar clearafter" style="margin-left:15px;height:94px">' +
        '<div class="teacher-search">' +
        '<p><a href="javascript:(void);">' + i18next.t('timetable.studentname') + '：</a><span id="studentname1" style="margin-right:15px;"></span>' +
        '<a href="javascript:(void);">' + i18next.t('table.course') + '：</a><span id="coursename1" style="margin-right:52px;"></span></p><br/>' +
        '<span>' + i18next.t('table.teacherquery') + '：</span>' +
        '<input type="text" id="J_date_search" class="form-control" data-type="date-input" data-tips="请选择日期范围" data-valuetype="range" readonly="" value="请选择日期范围" style="width: 210px;">' +
        '<select id="cource"></select>' +
        '</div>' +
        '</div>' +
        '<div class="wrap" id="appint_alert">' +
        '<table class="table" id="J_teacherlist_select">' +
        '<thead>' +
        '<th>' + i18next.t('table.no') + '</th>' +
        '<th>' + i18next.t('table.name') + '</th>' +
        '<th>' + i18next.t('table.starttime') + '</th>' +
        '<th>' + i18next.t('table.endtime') + '</th>' +
        '<th>' + i18next.t('table.remainingquota') + '</th>' +
        '<th>' + i18next.t('table.choice') + '</th>' +
        '</thead>' +
        '<tbody id="J_teacherlist_data"></tbody>' +
        '</table>' +
        '</div>' +
        '</div>' +
        '<div class="timelist-search" style="width: 42%; float: right; margin-left: 30px; border-bottom：none; height:auto;  border-left: 1px solid #ccc; margin-top: 20px;">' +
        '<h3 style="margin-left:15px;">'+i18next.t('table.make')+'</h3>' +
        '<div class="teacher" style="margin-left:15px;">' +
        '<span>'+i18next.t('table.teachername')+'：</span>' +
        '<span id="J_teachername"></span>' +
        '<ul class="teacherRemark" style="display:inline-block;margin-left:30px;"></ul>' +
        '</div>' +
        '<div class="duration" style="margin-left:15px;padding-bottom:3px!important"></div>' +
        '<div class="appoint-section23" style="margin-left:15px;" id="appint_sealert"></div>' +
        '</div>' +
        '<div style="width: 42%; float: right; margin-left: 30px; border-bottom：none; height: 980px;  border-left: 1px solid #ccc; margin-top: 20px;display:none" class="prompt">' +
        '<p style="margin-top:154px;margin-left:77px;">'+i18next.t('table.clickleft')+'</p>' +
        '</div>' +
        '</div>');
    var $orderEdit = $('<div class="paraList Nformstyle" id="J_enroll_wrap" >' +
        '<input class="form-control " type="hidden" name="orderuid">' +
        '<input class="form-control " type="hidden" name="studentuid" >' +
        '<div class="li Snameinput">' +
        '<div class="title  required">' +
        '<span>'+i18next.t('table.studentname')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control a1 focus studentname" data-formcheck="length" type="text" name="studentname"  readonly>' +
        '<div class="inputErrorTips" style="display: none;"></div>' +
        '</div>' +

        ' </div>' +
        '<div class="li">' +
        '<div class="title required">' +
        '<span>'+i18next.t('info.classinaccountnumber')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control focus a1" type="text" name="ClassInNo"  readonly>' +
        '<div class="inputErrorTips" style="display: none;"></div>' +
        '</div>' +
        '</div>' +
        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.classhour')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control a1" type="text" name="classhours" >' +
        '</div>' +
        '</div>' +
        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.giveclass')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control a1" type="text" name="classbonus" >' +
        '</div>' +
        '</div>' +
        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.coursename')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control a1" type="text" name="coursename" >' +
        '</div>' +
        '</div>' +

        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.entrydate')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input type="text" class="form-control a1" size="16" data-type="date-input" name="orderdate" data-valuetype="single" data-value="0" value="选择时间" readonly="readonly"  style="width:177px;">' +
        '</div>' +
        '</div>' +

        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.describes')+'：</span>' +
        '</div>' +
        '<div class="content">' +
        '<input class="form-control a1" type="text" name="description" >' +
        '</div>' +
        '</div>' +
        '<div class="li">' +
        '<div class="title">' +
        '<span>'+i18next.t('table.moneys')+'：</span>' +
        '</div>' +
        '<div class="content" style="position:relative;">' +
        '<input class="form-control a1" type="text" name="amount" style="padding-left:15px;width:177px" id="ordersinputpadding">' +
        '<span style="position:absolute;left:5px;top:6px" id="orderspanhide">￥</span>' +
        '</div>' +
        '</div>' +

        '</div>');
    $J_teacher_appoint.find('.line').css({
        "width": "1px",
        "height": "326px",
        "background": "#ccc",
        "position": "absolute",
        "left": "598px",
        "top": "30px",
        "z-index": "10000"
    });
    var $orderAdd;
    var uid;
    var currentid;
    var levels=[];
    $.ajax({
        url: "/api/user/current",
        type: "get",
        async: false,
        success: function (data) {
            uid = data.data.userid;
        }
    })
    $.ajax({
        url: "/api/student/user/" + uid,
        type: "get",
        async: false,
        success: function (data) {
            currentid = data.data.studentuid;
        }
    })

    //获取当前学生的课程信息
    getorderinfos();
    function getorderinfos(query) {
        ajaxMethod({
            url: '/api/appoint/myclasses/' + currentid,
            type: 'get',
            data: query,
            success: function (data) {
                var $enrollmentTable = $('#J_enrollment').html('')
                if (data.length == 0) {
                    var $div = $('<div style="font-size:14px;height:166px;border-top: 1px solid #ccc;line-height:166px;margin-top:19px;text-align: center;">您还没有购买课程,请先去够买课程!</div>').appendTo($enrollmentTable);
                } else {
                    getorderinfossuccess(data);
                }

            }
        })

        function getorderinfossuccess(data) {
            var $enrollmentTable = $('#J_enrollment').html('')
            var $thead = $('<thead>\
          <tr>\
            <th>'+i18next.t('table.no')+'</th>\
            <th>'+i18next.t('table.coursename')+'</th>\
            <th>'+i18next.t('table.classhours')+'</th>\
            <th>'+i18next.t('table.giveclass')+'</th>\
            <th>'+i18next.t('table.totalhours')+'<small style="font-size:6px;">'+i18next.t('table.classhoursadd')+'</small></th>\
            <th>'+i18next.t('table.appointmentclass')+'</th>\
            <th><a herf="javascript:(void);" >'+i18next.t('table.entrydate')+'</a></th>\
            <th>'+i18next.t('table.entryman')+'</th>\
            <th>'+i18next.t('table.handle')+'</th>\
         </tr>\
         </thead>').appendTo($enrollmentTable)
            var $tbody = $('<tbody></tbody>').appendTo($enrollmentTable);
            //data = JSON.parse(data)
            $.each(data, function (index, item) {
                var item = item.appoint;
                var classhours = Number(item.classhours);
                var classbonus = Number(item.classbonus)
                var coursename = "";
                if (item.coursename != "") {
                    coursename = item.coursename;
                } else {
                    coursename = "--";
                }
                var oruid = item.appointid;
                var studentuid = item.studentuid;
                var orderTime = formatTime(item.orderdate);
                var $enroll = $('<tr class="enroll" data-uid="' + oruid + '"   data-studentuid="' + studentuid + '"  id="oder' + oruid + '"></tr>')
                $enroll.append('<td>1</td>')
                // $enroll.append('<td>' + item.studentname + '</td>')
                // $enroll.append('<td>' + item.ClassInNo + '</td>')//这里的mobile实际是classInNo的字段
                $enroll.append('<td>' + coursename + '</td>')
                $enroll.append('<td>' + classhours + '</td>')
                $enroll.append('<td>' + classbonus + '</td>')
                $enroll.append('<td>' + (classhours + classbonus) + '</td>')
                var $alreadyhours = $('<td ><input type="button" class="btn btn-primary btn-sm btn-inverse appointhours"  value=' + (item.consumed) + '  style="background:#fff;"></td>').appendTo($enroll);
                // $enroll.append('<td>' + (item.resthours<=0?"0":item.resthours) + '</td>')//剩余课时
                $enroll.append('<td>' + orderTime.substr(0, 10) + '</td>')
                $enroll.append('<td>' + item.creator + '</td>')
                var $bookbtn = $('<td ><input type="button"  value="约课" class="ml5 btn btn-primary btn-sm btn-inverse" levels="'+(item.levels)+'"  nam="arrbook" style="background:#fff;"></td>').appendTo($enroll);
                $bookbtn.find('input').val(i18next.t('table.aboutclass'));
                var $handleTd = $('<td></td>').appendTo($enroll);
                var $deletebtn = $('<a class="ml5 editOrder" style="display:none"><span class="btn btn-primary btn-sm btn-inverse" >'+i18next.t('table.edit')+'</span></a>').appendTo($handleTd);
                var $debtn = $('<a href="javascript:(void);" style="display:none"><span class="	btn btn-danger btn-sm btn-inverse">'+i18next.t('table.delete')+'</span></a>').appendTo($handleTd);
                var sumn = (classhours + classbonus);
                var inputVlue = parseInt($alreadyhours.find('input').val());
                if (inputVlue >= sumn) {
                    $bookbtn.find("input").attr("disabled", "disabled");
                } else {
                    $bookbtn.find("input").removeAttr("disabled");
                }
                //点击约课
                $bookbtn.on('click', function () {
                    $J_teacher_appoint.find("#oruid").val(item.appointid);
                    $J_teacher_appoint.find(".studentuid").val(studentuid);
                    $J_teacher_appoint.find('#studentname').val(item.studentname);
                    $J_teacher_appoint.find('#coursename').val(item.coursename);
                    var levels=[];
                    levels.push($(this).children().attr("levels").split(","));
                    levels=[].concat.apply([],levels)
                    if(levels==""){
                        _Tips("请联系机构人员为您设置约课级别！");
                        return false;
                    }
                    $J_teacher_appoint.attr("levels",levels);
                    appointTeacher(undefined,"","",levels);//按照时间选择老师
                    coursetypes();//按照课程类型选择老师
                    var popUpBox = new PopUpBox({
                        type: 'dom',
                        style: 'default autoResize',
                        submitBtnType: 'alert',
                        closeClear: false,
                        titleText: i18next.t('popupbox.pleaseselectteacher'),//'请选择老师'
                        show: true,
                        content: $J_teacher_appoint,
                        callback: {
                            yes: function (e) {
                                window.location.reload();
                            }

                        },
                        position: {
                            width: 1042,
                            height: 510,
                        }
                    })
                    popUpBox.submitBtnBox.$dom.css('text-align', 'right')
                })
                //点击编辑按钮
                $deletebtn.on('click', function () {
                    loadEnrollData(oruid);
                    var popUpBox = new PopUpBox({
                        type: 'dom',
                        style: 'default contentScroll',
                        submitBtnType: 'confirm',
                        titleText:i18next.t('popupbox.editcontent'),// '请输入编辑内容'
                        show: true,
                        content: $orderEdit,
                        callback: {
                            yes: function (e) {
                                // alert(this);
                                bindSubmit();
                                window.location.reload();

                            }
                        },
                        position: {
                            width: 667,
                            height: 352
                        }
                    })
                })
                //点击删除按钮
                $debtn.on('click', function () {
                    var popUpBox = new PopUpBox({
                        type: 'dom',
                        style: 'default contentScroll',
                        submitBtnType: 'confirm',
                        titleText: i18next.t('popupbox.warmprompt'),//'温馨提示'
                        show: true,
                            content: '<div style="margin-left:27px;margin-top:34px;">'+i18next.t('popupbox.studentinfo')+'</div>',//学生信息会一并删除，确定要删除吗？
                        callback: {
                            yes: function (e) {
                                ajaxMethod({
                                    url: "/api/appointment/" + oruid,
                                    type: "delete",
                                    success: function () {
                                        getorderinfos();

                                    }
                                });
                            }
                        },
                        position: {
                            width: 448,
                            height: 226
                        }
                    })


                })
                $tbody.append($enroll);
                //table排序
                var len = $('table tr').length;
                for (var i = 1; i < len; i++) {
                    $('table tr:eq(' + i + ') td:first').text(i);
                }

                //处理空数据
                $tbody.find("tr").each(function () {
                    var tdhtml = $(this).children();
                    $.each(tdhtml, function (i, t) {
                        //console.log($(t).text());
                        $(t).text() == 'null' ? $(t).text('--') : $(t).text()
                        $(t).text() == 'NaNaN-aN-a' ? $(t).text('--') : $(t).text()
                        $(t).text() == ' ' ? $(t).text('--') : $(t).text()
                        $(t).text() == '0000-00-00' ? $(t).text('--') : $(t).text()

                    })
                });
                //已约课按钮设置
                var $appointhours = $alreadyhours.find("input");
                if (item.consumed == 0) {
                    $appointhours.attr('disabled', true);
                } else {
                    $appointhours.attr('disabled', false);
                }

                //点击已约课时数量
                $alreadyhours.on("click", function () {
                    ajaxMethod({
                        url: '/api/appointment/' + oruid + '/appints',
                        type: 'get',
                        dataType: 'json',
                        success: function (data) {
                            var $div = $('<div class="Yuelist wrap"></div>')
                            ajaxMethod({
                                url: '/api/appointment/' + item.appointid + '/lessons',
                                type: 'get',
                                success: function (json) {
                                    var $table = $('<table class="table enrollment" id="YueClasslist" style="margin-top:15px;"></table>').appendTo(($div));
                                    ;
                                    var $thead = $('<thead>\
                                     <tr>\
                                       <th>'+i18next.t('table.no')+'</th>\
                                       <th>'+i18next.t('table.teachername')+'</th>\
                                       <th>'+i18next.t('table.lessonsname')+'</th>\
                                       <th>'+i18next.t('table.startdate')+'</th>\
                                       <th>'+i18next.t('table.time')+'</th>\
                                       <th>'+i18next.t('table.duration')+'</th>\
                                       <th>'+i18next.t('table.handle')+'</th>\
                                     </tr>\
                                     </thead>').appendTo($table);
                                    var $tbody = $('<tbody></tbody>').appendTo($table);

                                    function getDurationMinute(begintime, endtime) {
                                        if (begintime != null || endtime != null) {
                                            var begintime = +new Date(begintime.replace(' ', ' '));
                                            var endtime = +new Date(endtime.replace(' ', ' '));
                                            return (endtime - begintime) / (60 * 1000) + '分钟';
                                        } else {
                                            return '--';
                                        }
                                    }

                                    $.each(data, function (index, item) {

                                        var id = item.id;
                                        //console.log(item);
                                        var uid = item.scheduleid;
                                        //var bgT = formatTime(item.begintime)
                                        //var edT = formatTime(item.endtime)
                                        var begintime = new Date(item.begintime).Format('YYYY-MM-DD hh:mm')
                                        var endtime = new Date(item.endtime).Format('YYYY-MM-DD hh:mm');
                                        var $valuetr = $('<tr class="enroll" data-uid="' + uid + '"></tr>')
                                        $valuetr.append('<td>1</td>')
                                        $valuetr.append('<td>' + item.teacher + '</td>')
                                        var $lesson_td = $('<td></td>').appendTo($valuetr)
                                        $valuetr.append('<td>' + begintime.substr(0, 10) + ' </td>')
                                        $valuetr.append('<td>' + begintime.substr(11, 5) + '</td>')
                                        $valuetr.append('<td>' + getDurationMinute(item.begintime, item.endtime) + '</td>')
                                        var $affirm = $('<td><input type="button" class="ml5 btn btn-warning" value="取消" data-i18n="[value]table.cancel"></input></td>').appendTo($valuetr);
                                        $.each(json, function (ind, it) {
                                            if (item.scheduleid == it.scheduleid) {
                                                var $a_lessonname = $('<a>' + it.name + '</a>').appendTo($lesson_td);
                                            }
                                        })
                                        $affirm.on('click', function () {
                                            ajaxMethod({
                                                url: '/api/appointment/' + id + '/unappint',
                                                type: 'put',
                                                success: function (data, status) {
                                                    if (status.code != 0) {
                                                        var popUpBox = new PopUpBox({
                                                            type: 'dom',
                                                            style: 'default contentScroll',
                                                            submitBtnType: 'confirm',
                                                            titleText:i18next.t('popupbox.systemmessages') ,//'系统提示'
                                                            show: true,
                                                            content: '<p style="margin-left:18px;margin-top:21px;">'+i18next.t('popupbox.nocancel')+'</p>',//该课程已经结束或正在上课，不能取消！
                                                            callback: {
                                                                yes: function (e) {
                                                                }
                                                            },
                                                            position: {
                                                                width: 435,
                                                                height: 300
                                                            }
                                                        })
                                                        $(".btn-default").css({
                                                            'border': '1px solid #ccc'
                                                        });

                                                    } else {
                                                        $affirm.find('input').attr('disabled', true);
                                                    }
                                                }
                                            })
                                        })
                                        $tbody.append($valuetr);
                                        //table排序
                                        var len = $div.find('table tr').length;
                                        for (var i = 1; i < len; i++) {
                                            $div.find('table tr:eq(' + i + ') td:first').text(i);
                                        }
                                    })//结束
                                }
                            })
                            //弹出层
                            var popUpBox = new PopUpBox({
                                type: 'dom',
                                style: 'default contentScroll',
                                submitBtnType: "alert",
                                //submitBtnType: 'alert',
                                titleText: ''+i18next.t('table.coursename')+':　<span>' + item.coursename + '</span>',
                                show: true,
                                content: $div,
                                callback: {
                                    yes: function (e) {
                                        window.location.reload();
                                    }
                                },
                                position: {
                                    width: 871,
                                    height: 400
                                }
                            })
                            $(".submitBtnBox").css({
                                'text-align': 'right'
                            });
                        }
                    })
                })
            })
            //把所有null的字段都换成---
            $tbody.find("tr").each(function () {
                var tdhtml = $(this).children();
                $.each(tdhtml, function (i, t) {
                    $(t).text() == 'null' ? $(t).text('--') : $(t).text()
                    $(t).text() == '1970-01-01' ? $(t).text('--') : $(t).text()
                })
            });

        }

    }

    //报名表列表导入功能
    function fileUpload($container) {
        var $uploadInput = $container.find('input')
        var coverUploadInput = new UploadInput({
            formData: {
                importer: 'appoint'
            },
            $dom: $uploadInput,
            done: function (uploadSrc) {
                console.log(uploadSrc);
                window.location.reload();
            }
        });
    }

    fileUpload($('#J_container'))
    //添加学生
    $("#orderadd").on("click", function () {
        $orderAdd = $('<div class="paraList">' +
            '<input class="form-control " type="hidden" name="orderuid">' +
            '<input class="form-control " type="hidden" name="studentuid" >' +
            '<div class="li line">' +
            '<div class="title">' +
            '<label style="color:red";position: relative;left: -2px;>*</label><span>'+i18next.t('table.studentname')+'</span>' +
            '</div>' +
            '<div class="content" id="j-studencontainer">' +
            '<span class="btn btn-default" id="j-addstudent">'+i18next.t('table.addstudent')+'</span>' +
            '</div>' +
            '</div>' +
            '<div class="li">' +
            '<div class="title">' +
            '<label style="color:red";position: relative;left: -2px;>*</label><span>'+i18next.t('table.classhours')+'</span>' +
            '</div>' +
            '<div class="content">' +
            '<input class="form-control a1" type="text" name="classhours" >' +
            '</div>' +
            '</div>' +
            '<div class="li">' +
            '<div class="title">' +
            '<span>'+i18next.t('table.giveclass')+'</span>' +
            '</div>' +
            '<div class="content">' +
            '<input class="form-control a1" type="text" name="classbonus" >' +
            '</div>' +
            '</div>' +
            '<div class="li">' +
            '<div class="title">' +
            '<span>'+i18next.t('table.coursename')+'</span>' +
            '</div>' +
            '<div class="content">' +
            '<input class="form-control a1" type="text" name="coursename" >' +
            '</div>' +
            '</div>' +

            '<div class="li">' +
            '<div class="title">' +
            '<span>'+i18next.t('table.entrydate')+'</span>' +
            '</div>' +
            '<div class="content">' +
            '<input type="text" class="form-control a1" size="16" data-type="date-input" name="orderdate" data-valuetype="single" data-value="0" value="选择时间" readonly="readonly"  style="width:170px;">' +
            '</div>' +
            '</div>' +

            '<div class="li">' +
            '<div class="title">' +
            '<span>'+i18next.t('table.describe')+'</span>' +
            '</div>' +
            '<div class="content">' +
            '<input class="form-control a1" type="text" name="description" ">' +
            '</div>' +
            '</div>' +
            '<div class="li">' +
            '<div class="title">' +
            '<span>'+i18next.t('table.money')+'</span>' +
            '</div>' +
            '<div class="content" style="position:relative;">' +
            '<input class="form-control a1" type="text" name="amount" style="padding-left:15px;width:177px" id="ordersinputpadding" >' +
            '<span style="position:absolute;left:5px;top:7px" id="orderspanhide">￥</span>' +
            '</div>' +
            '</div>' +
            '</div>');
        var newda = new Date().Format('YYYY-MM-DD');
        $orderAdd.find('[name=orderdate]').val(newda);

        var $addStudentBtn = $orderAdd.find('#j-addstudent')
        var studentViewList = new ContactViewList({
            hasAvatar: true,
            editable: false
        })

        $addStudentBtn.after(studentViewList.$dom.addClass('inline-block').addClass('cursor-pointer'))

        function studentSelect() {
            ajaxMethod({
                url: '/api/students',
                success: function (data) {
                    var candidateStudentList = []
                    $.each(data.list, function (i, item) {
                        console.log(item);
                        candidateStudentList.push({
                            id: item.studentuid,
                            avatar: 'img/avatar.png',
                            name: item.name,
                            phone: item.ClassInNo
                        })
                    })

                    var studentSelector = new ContactSelector({
                        candidateDataList: candidateStudentList,
                        checkedDataList: studentViewList.getDataList(),
                        checkedMax: 1,
                        callback: {
                            submit: function (checkedDataList) {
                                if (!Object.keys(checkedDataList).length) {
                                    _Tips(i18next.t('popupbox.pleaseselect'));//'请选择'
                                    return false
                                }
                                console.log(checkedDataList);
                                $addStudentBtn.hide()

                                studentViewList.update(checkedDataList)
                            }
                        }
                    })
                    studentSelector.$titleText.html(i18next.t('table.addstudent'))//添加学生
                    studentSelector.popUpBox.show();
                }
            })
        }


        $addStudentBtn.on('click', function () {
            studentSelect();
        })

        studentViewList.$dom.on('click', function () {
            studentSelect();
        })


        var popUpBox = new PopUpBox({
            type: 'dom',
            style: 'default contentScroll',
            submitBtnType: 'confirm',
            titleText:i18next.t('popupbox.pleasecontent') ,//请填写内容
            show: true,
            content: $orderAdd,
            callback: {
                yes: function (e) {
                    var $contact = $orderAdd.find('.contact');

                    function add() {
                        var appointid = $orderAdd.find('[name=orderuid]').val()
                        var orderstatus = $orderAdd.find('[name=orderstatus]').val()
                        var studentuid = $contact.attr('data-contactid');
                        var studentname = $contact.find('.name').text();
                        var mobile = $contact.find('.description').text();//选框组件
                        var classhours = $orderAdd.find('[name=classhours]').val()
                        var classbonus = $orderAdd.find('[name=classbonus]').val()
                        var courseid = $orderAdd.find('[name=courseid]').val()
                        var coursename = $orderAdd.find('[name=coursename]').val()
                        var orderdate = $orderAdd.find('[name=orderdate]').val()
                        var description = $orderAdd.find('[name="description"]').val()
                        var amount = $orderAdd.find('[name=amount]').val();
                        var Studentroll = {
                            orderstatus: orderstatus,
                            studentuid: studentuid,
                            studentname: studentname,
                            mobile: mobile,
                            classbonus: classbonus,
                            classhours: classhours,
                            courseid: courseid,
                            coursename: coursename,
                            orderdate: orderdate,
                            description: description,
                            amount: amount
                        };
                        ajaxMethod({
                            url: '/api/appointment',
                            type: 'post',
                            data: Studentroll,
                            success: function (data) {
                                window.location.reload();
                                //alert('添加成功')
                            }
                        });
                    }

                    var studentname = $contact.find('.name').text();
                    var classhours = $orderAdd.find('[name=classhours]').val();
                    if (studentname != "" || classhours != "") {
                        add();
                    } else {
                        return false;
                    }
                }
            },
            position: {
                width: 667,
                height: 352
            }
        })
    })

    function loadEnrollData(oruid, callback) {
        console.log(oruid)
        ajaxMethod({
            url: '/api/appointment/' + oruid,
            dataType: 'json',
            success: function (data) {
                $orderEdit.find('[name=orderuid]').val(data.appointid);
                $orderEdit.find('[name=orderstatus]').val(data.orderstatus);
                $orderEdit.find('[name=studentuid]').val(data.studentuid);
                $orderEdit.find('[name=studentname]').val(data.studentname);
                $orderEdit.find('[name=ClassInNo]').val(data.mobile);
                $orderEdit.find('[name=classhours]').val(data.classhours);
                $orderEdit.find('[name=classbonus]').val(data.classbonus);
                $orderEdit.find('[name=courseid]').val(data.courseid);
                $orderEdit.find('[name=coursename]').val(data.coursename);
                $orderEdit.find('[name=description]').val(data.description);
                $orderEdit.find('[name=amount]').val(data.amount);
                var orderdate = "";
                if (data.orderdate != "0000-00-00 00:00:00") {
                    orderdate = data.orderdate.substr(0, 10)
                } else {
                    return i18next.t('popupbox.pleasedate');//请选择日期
                }
                $orderEdit.find('[name=orderdate]').val(orderdate);
                (typeof callback == 'function') && callback()
            }
        })
    }

    //编辑学生
    function bindSubmit(data) {
        if (FormCheck.childrenInputCheck($orderEdit.find('#J_enroll_wrap'))) {
            var appointid = $orderEdit.find('[name=orderuid]').val()
            var orderstatus = $orderEdit.find('[name=orderstatus]').val()
            var studentuid = $orderEdit.find('[name=studentuid]').val()
            var studentname = $orderEdit.find('[name="studentname"]').val()
            var ClassInNo = $orderEdit.find('[name=mobile]').val()
            var classhours = $orderEdit.find('[name=classhours]').val()
            var classbonus = $orderEdit.find('[name=classbonus]').val()
            var courseid = $orderEdit.find('[name=courseid]').val()
            var coursename = $orderEdit.find('[name=coursename]').val()
            var orderdate = $orderEdit.find('[name=orderdate]').val()
            var description = $orderEdit.find('[name="description"]').val()
            var amount = $orderEdit.find('[name=amount]').val()
            var Studentroll = {
                orderstatus: orderstatus,
                studentuid: studentuid,
                studentname: studentname,
                mobile: ClassInNo,
                classbonus: classbonus,
                classhours: classhours,
                courseid: courseid,
                coursename: coursename,
                orderdate: orderdate,
                description: description,
                amount: amount
            }
            if (appointid != undefined) {
                ajaxMethod({
                    url: '/api/appointment/' + appointid,
                    type: 'put',
                    data: $.extend(Studentroll, {appointid: appointid}),
                    success: function (data) {
                        //alert('修改成功')
                    }
                });

            }

        }
    }

    var scheduleidarr = [];
    //以下是点击预约的controller
    var checkedList = new Array();

    function getEnrollList(arr) {
        ajaxMethod({
            url: '/api/schedules/teachertimes',
            type: 'get',
            dataType: 'json',
            data: arr,
            success: function (data, arr) {
                var $enrollmentTable1 = $J_teacher_appoint.find('.appoint-section23').html('');
                var days = data.days;
                $.each(days, function (index, item) {
                    var a = JSON.stringify(item.day)
                    var day = (item.day).replace(/\-/g, "");
                    var $div = $('<div data-id=' + day + '></div>').appendTo($enrollmentTable1);
                    $div.append('<h4 style="margin-top:43px;">' + item.day + ' (' + item.week + ') ' + '</h4>');
                    var list = item.list;
                    $.each(list, function (index2, item2) {
                        var $p = $("<p style='height:41px;margin:24px 0;'></p>").appendTo($div);
                        var spn1 = $('<span class="spn1" style="display:inline-block;width:337px;line-height:24px;"></span>').appendTo($p);
                        spn1.append('<span style="width:161px;display:inline-block;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;position:relative;top:5px;">'+i18next.t('table.coursetype')+':' + item2.coursetypename + '</span>');
                        var $lessonName = $('<span style="margin-top:10px;cursor:pointer" class="cursor-edit">'+i18next.t('table.lessonsname')+'：<span style="max-width:68px;display: inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;position: relative;top: 10px;" class="J_lesson">' + item2.name + '</span></span><br/>')
                        $lessonName.on('click', function () {
                            var beforeVal = item2.name;
                            var $content = $('<div class="formList">\
                     <div class="formLi">\
                       <div class="formTitle">\
                         <span>'+i18next.t('table.lessonsname')+'</span>\
                       </div>\
                       <div class="formContent">\
                         <input class="form-control" type="text" name="lessonname" value="' + beforeVal + '" style="width:300px;">\
                       </div>\
                     </div>\
                   </div>');
                            var $input = $content.find('[name="lessonname"]');
                            var popUpBox = new PopUpBox({
                                type: 'dom',
                                style: 'default',
                                submitBtnType: 'confirm',
                                titleText:i18next.t('popupbox.edit'),//编辑课节名称
                                content: $content,
                                show: true,
                                callback: {
                                    'yes': function (e) {
                                        var curVal = $.trim($input.val());
                                        if (curVal == beforeVal) {
                                            _Tips(i18next.t('popupbox.nochange'));//'课节名称无变化'
                                            return false;
                                        }

                                        if (curVal == '') {
                                            _Tips(i18next.t('popupbox.lessonnoempty'));//'课节名称不能为空'
                                            return false
                                        }

                                        ajaxMethod({
                                            url: '/api/schedule/' + item2.scheduleid,
                                            method: 'put',
                                            data: $.extend(item2, {name: curVal}),
                                            success: function (data, status) {
                                                if (status.code == 0) {
                                                    $lessonName.find('.J_lesson').text(data.name)
                                                    popUpBox.close()
                                                }
                                            }
                                        })

                                    }
                                },
                                position: {
                                    width: 420,
                                    height: 200
                                }
                            })
                        })
                        spn1.append($lessonName)
                        spn1.append('<span style="padding-right:29px;padding-left:4px;width:161px;display:inline-block;">'+i18next.t('table.time')+':' + (item2.begintime.substr(11, 5)) + '~' + (item2.endtime.substr(11, 5)) + '</span>');
                        spn1.append('<span style="" >'+i18next.t('table.remainingquota')+'：<a class="quotas">' + item2.quotas + '</a></span>');
                        if(!localStorage.lang){
                            localStorage.setItem('lang','zh');
                        }
                        if(localStorage.lang && localStorage.lang=="zh"){
                            var $appointBtn1 = $('<input type="button" data-i18n="[value]table.make"  value="预约" class="btn btn-primary yue" style="position: relative;left: 14px;top: -11px;">').appendTo($p);
                        }else{
                            var $appointBtn1= $('<input type="button" data-i18n="[value]table.make"  value="预约" class="btn btn-primary yue" style="position: relative;left: 170px;top: 0px;">').appendTo($p);
                        }
                        $appointBtn1.val(i18next.t('table.make'))
                        for (var i = 0; i < scheduleidarr.length; i++) {
                            if (scheduleidarr[i] == item2.scheduleid) {
                                $appointBtn1.attr("disabled", "disabled");
                                $appointBtn1.val(i18next.t('table.reservation'));//"已预约"
                            }
                        }
                        var quotas = 0;
                        $appointBtn1.on('click', function () {
                            quotas = $(this).prev('span').find('.quotas').html() - 1;
                            if (quotas < 0) {
                                quotas = 0;
                            }
                            $(this).prev('span').find('.quotas').html(quotas);
                            var oruid = $J_teacher_appoint.find("#oruid").val();
                            var studentuid = $J_teacher_appoint.find(".studentuid").val();
                            ajaxMethod({
                                url: "/api/appointment/" + oruid + "/appint",
                                dataType: "json",
                                type: 'put',
                                data: {"scheduleid": item2.scheduleid},
                                success: function (data, status) {
                                    if (status.code == 0) {
                                        $appointBtn1.css({
                                            "background": "#ccc",
                                            "border": "1px solid #ccc",
                                            "color": "#fff",
                                            "disabled": "disabled"
                                        });
                                        $appointBtn1.html(i18next.t('table.reservation'));//"已预约"
                                    } else if (status.code == 1) {
                                        //alert(i.message);
                                        var popUpBox = new PopUpBox({
                                            type: 'dom',
                                            style: 'default',
                                            submitBtnType: 'confirm',
                                            titleText:i18next.t('popupbox.edit'),//'编辑课节名称'
                                            content: '<div style="margin-left:20px;margin-top:20px;">' + (status.message) + '</div>',
                                            show: true,
                                            callback: {
                                                'yes': function (e) {
                                                    window.location.reload();
                                                }
                                            },
                                            position: {
                                                width: 420,
                                                height: 200
                                            }
                                        })

                                    }

                                }
                            })
                        })

                    })


                })

                //排序
                function big() {
                    var tr = $enrollmentTable1.find("div");
                    var initList = [], domArr = [];

                    $.each(tr, function (a, k) {
                        initList[a] = $(this).attr('data-id');

                    })
                    /* 从小到大排序*/
                    function bigToSmall() {
                        getDom();
                        $.each(domArr, function (i) {
                            $.each(domArr, function (j) {
                                if (domArr[i].attr('data-id') < domArr[j].attr('data-id')) {
                                    mid = domArr[j];
                                    domArr[j] = domArr[i];
                                    domArr[i] = mid;
                                }

                            })
                        })
                        appendDom()
                    }

                    /*取出所有tr放进数组*/
                    function getDom() {
                        $(tr).each(function (m) {
                            domArr[m] = $(this);
                        })
                    }

                    /*将数组中的tr插入tbody(原ul中的li自动删除。DOM元素的特性。) */
                    function appendDom() {
                        $.each(domArr, function (d) {
                            $enrollmentTable1.append(domArr[d]);
                        })
                    }

                    bigToSmall();
                }

                big();

            }
        })
    }

    //按照类型选择老师
    function coursetypes() {
        ajaxMethod({
            url: '/api/coursetypes',
            type: "get",
            dataType: "json",
            success: function (data) {
                cource(data);
            }

        })
        function cource(data) {
            //console.log(data)
            var $cource = $('#cource').html('');
            $('<option>'+i18next.t('table.all')+'</option>').appendTo($cource);
            $cource.css({
                "width": "120px",
                "height": "30px",
                "border": "1px solid #ccc",
                "border-radius": "3px"

            });

            $.each(data, function (index, item) {
                //console.log(item.coursetypeuid);
                $('<option data-cuid=' + item.coursetypeuid + '>' + item.coursetypename + '</option>').appendTo($cource);

            })
            $('#cource').on('change', function () {
                var sCoursetypename = $('#cource option:selected').val();
                var sCoursetypeid = $('#cource option:selected').attr('data-cuid');
                var getVal = $J_teacher_appoint.find("#J_date_search").val();
                appointTeacher(getVal.split('~')[0], getVal.split('~')[1], sCoursetypeid);
            })
        }
    }

    //按照时间选择老师
    function appointTeacher(begintime, endtime, sCoursetypeid,levels) {
        if (begintime == undefined) {
            begintime = new Date().Format('YYYY-MM-DD')
            endtime = new Date(+new Date + 30 * 24 * 3600 * 1000).Format('YYYY-MM-DD')

            $J_teacher_appoint.find('#J_date_search').val(begintime + '~' + endtime)
        }

        ajaxMethod({
            url: '/api/schedules/teachers',
            data: {
                begintime: begintime,
                endtime: endtime,
                coursetypeid: sCoursetypeid,
                levels:levels
            },
            success: function (data) {
                formatData(data, sCoursetypeid);
            }
        })

        function formatData(data, sCoursetypeid) {
            var $teacherListData = $J_teacher_appoint.find('#J_teacherlist_data').html('')
            $.each(data, function (index, item) {
                var studentname = $J_teacher_appoint.find('#studentname').val();
                var coursename = $J_teacher_appoint.find('#coursename').val();
                $J_teacher_appoint.find("#studentname1").html(studentname);
                $J_teacher_appoint.find("#coursename1").html(coursename);
                var teacheruid = item.teacherid;
                var $tr = $('<tr id="id' + item.teacherid + '" data-uid="' + item.teacherid + '"></tr>')
                $tr.append('<td>1</td>')
                $tr.append('<td>' + item.teachername + '</td>')
                //$tr.append('<td>' + item.mobile + '</td>')
                $tr.append('<td>' + item.begintime + '</td>')
                $tr.append('<td>' + item.endtime + '</td>')
                $tr.append('<td>' + item.times + '</td>')
                var $radioTd = $('<td></td>').appendTo($tr)
                var $radioIcon = $('<span class="icon icon-size-16 icon-radio" data-type="checkbox" style="position:relative !important;left:3px;">\
               <input type="checkbox" name="teacher" data-checkedmax="1" value="1">\
               </span>').appendTo($radioTd);
                //点击小点
                $radioIcon.on('click', function () {
                    var oruid = $J_teacher_appoint.find("#oruid").val();
                    //alert(oruid);
                    ajaxMethod({
                        url: "/api/appointment/" + oruid + "/appints",
                        type: "get",
                        dataType: "json",
                        success: function (data) {
                            $.each(data, function (index, item) {
                                scheduleidarr.push(item.scheduleid);

                            })

                        }

                    })


                    if ($(this).hasClass('checked')) {
                        $J_teacher_appoint.find('.timelist-search').hide();
                        $J_teacher_appoint.find('.line').show();
                    } else {
                        $J_teacher_appoint.find('#J_teachername').text(item.teachername);
                        $J_teacher_appoint.find('.timelist-search').show();
                        $J_teacher_appoint.find('.line').hide();

                        teacherlist(sCoursetypeid);
                        $('#J_appointTimeList').click()
                        var $parentDom = $J_teacher_appoint.find('.appoint-section').html('');
                        var $teacherRemark = $J_teacher_appoint.find('.teacherRemark').html('');
                        var id = item.teacherid;
                        ajaxMethod({
                            url: "/api/teacher/" + id,
                            type: "get",
                            success: function (data) {
                                $('<a>'+i18next.t('table.remark')+'：</a><li style="display:inline-block;">' + data.remark1 + ' ,</li><li  style="display:inline-block;padding:0 4px;">' + data.remark2 + '</li>').appendTo($teacherRemark);
                            }
                        })
                    }
                })


                function teacherlist(sCoursetypeid) {
                    var arr = {
                        begintime: item.begintime,
                        endtime: item.endtime,
                        teacherid: item.teacherid,
                        coursetypeid: sCoursetypeid
                    }

                    $('.timelist-search').show()
                    $('.prompt').hide();
                    $('#J_appointTimeList').click()
                    getEnrollList(arr);
                }


                $teacherListData.append($tr)
                var $J_teacherlist_select = $J_teacher_appoint.find('#J_teacherlist_select');
                var len = $J_teacherlist_select.find('tr').length;
                for (var i = 1; i < len; i++) {
                    $J_teacherlist_select.find('tr:eq(' + i + ') td:first').text(i);
                }

            })
        }


    }
    $J_teacher_appoint.find('#J_date_search').on('change', function () {
        var getVal = $(this).val()
        var levels=[];
        levels.push($(this).parents("#J_teacher_appoint").attr("levels").split(","));
        levels=[].concat.apply([],levels)
        appointTeacher(getVal.split('~')[0], getVal.split('~')[1],'',levels)
    })

})
